<?php

namespace app\admin\controller;

use app\common\model\Domains;
use app\common\model\Videos;
use app\common\model\Users;
use app\common\model\Last;
use app\common\model\Pinglun;
use think\Db;
use think\Request;

class Video extends Base
{

    public function index(Request $request)
    {
        if ($post = $request->isAjax()) {

            $page = input('param.page/d', 1);
            $limit = input('param.limit/d', 20);
            $arttitle = input('param.title', "");
            $adminuser = input('param.adminuser', "");
            $adminid = input('param.admin/d', 0);
            $sortField = input('param.sortField', '');
            $newwhere = [];
            if ($arttitle != "") {
                $newwhere = [
                    ["title", "like", "%$arttitle%"]
                ];
            }
            if ($adminuser != "") {
                $where = [
                    ["username", "=", $adminuser]
                ];
                $videoadmin = Users::where($where)->find();
                if (!$videoadmin) {
                    error('没有找到该用户');
                }
                $newwhere = [
                    ["admin", "=", $videoadmin->id]
                ];
            }
            if ($adminid != "") {
                $newwhere = [
                    ["admin", "=", $adminid]
                ];
            }
            if ($sortField == 'view') {
                $neworder =
                    ['view' => 'desc'];

            } else {
                $neworder =
                    ['id' => 'desc'];


            }
            if (session('admin')->id == 1) {
                $arrs = Videos::where($newwhere)->order($neworder)->page($page)->limit($limit)->select();
                $count = Videos::where($newwhere)->count('id');
            } else {
                $arrs = Videos::where(['admin' => session('admin')->id])->where($newwhere)->order(['id' => 'desc'])->page($page)->limit($limit)->select();
                $count = Videos::where(['admin' => session('admin')->id])->where($newwhere)->count('id');
            }


            if (count($arrs) > 0) {
                foreach ($arrs as $k => $v) {
                    $v['domain'] = Domains::getOneData(2, true, $v['admin']);
                    $v['adminname'] = db('users')->where(['id' => $v['admin']])->value('username');
                }
            }

            $data = array(
                'data' => $arrs,
                'count' => $count,
                'code' => 0,
                'msg' => '',
            );
            return json($data);
        }

        return view();
    }

    // 通用删除（单纯的记录删除）
    public function del()
    {
        //获取参数
        $id = input('param.id/a', '');

        //如果缺少参数,报错
        if (empty($id)) {
            error('缺少参数,没有指定id或table');
        }

        //删除指定id
        $res = Db::name("videos")->delete($id);
        if ($res) {
            success('删除成功');
        } else {
            error('删除失败');
        }
    }


    // 添加、保存数据
    public function create(Request $request)
    {

        if ($request->isPost()) {
            $post = trimAll($request->post());
            $post['alias'] = getRandStr(8);
            if (session('admin')->id == 1) {

            } else {
                $post['admin'] = session('admin')->id;
            }


            unset($post['file']);

            //写入数据库
            if (Videos::create($post)) {
                createLog('添加 视频 成功：' . $post['title']);
                success('操作成功');
            } else {
                createLog('添加 视频 失败：' . $post['title']);
                error('操作失败');
            }

        }

        return view();
    }


    // 编辑、保存数据
    public function edit(Request $request, $id)
    {

        if ($request->isPost()) {
            $post = trimAll($request->post());
            if (session('admin')->id == 1) {

            } else {
                $post['admin'] = session('admin')->id;
            }

            unset($post['file']);

            //写入数据库
            if (Videos::where('id', $id)->update($post)) {
                createLog('编辑 视频 成功：' . $post['title']);
                success('操作成功');
            } else {
                createLog('编辑 视频 失败：' . $post['title']);
                error('操作失败');
            }

        }

        //加载数据
        $data = Videos::get($id);

        $this->assign('data', $data);
        return view();
    }

    public function updateUrl()
    {
        $type = request()->get("type");
        $ids = request()->post("ids");
        $tourl = request()->post('tourl');
        $newShreUrl = request()->post("new_shre_url");
        $shareEndUrl = request()->post("share_end_url");
        $backJumpUrl = request()->post("back_jump_url");
        if ($type == "zt") {
            Videos::where('id', 'in', $ids)->data(["tourl" => $tourl])->update();
        } else {
            Videos::where('id', 'in', $ids)
                ->data(["new_shre_url" => $newShreUrl, 'share_end_url' => $shareEndUrl, 'back_jump_url' => $backJumpUrl])
                ->update();
        }
        success('操作成功');
    }

    public function setjx()
    {
        $ids = request()->post("ids");
        $type = request()->get("type");
        if ($type == "set") {
            $data = Videos::where('id', 'in', $ids)->data(["is_jx" => 1])->update();
        } else {
            $data = Videos::where('id', 'in', $ids)->data(["is_jx" => 0])->update();
        }
        success('操作成功');
    }

    public function lastindex(Request $request)
    {
        if ($post = $request->isAjax()) {

            $page = input('param.page/d', 1);
            $limit = input('param.limit/d', 20);
            if (session('admin')->id == 1) {
                $arrs = Last::order(['id' => 'desc'])->page($page)->limit($limit)->select();
            } else {
                $arrs = Last::where(['admin' => session('admin')->id])->order(['id' => 'desc'])->page($page)->limit($limit)->select();
            }


            if (count($arrs) > 0) {
                foreach ($arrs as $k => $v) {
                    $v['domain'] = Domains::getOneData(2, true, $v['admin']);
                    $v['adminname'] = db('users')->where(['id' => $v['admin']])->value('username');
                }
            }

            $data = array(
                'data' => $arrs,
                'count' => Last::count('id'),
                'code' => 0,
                'msg' => '',
            );
            return json($data);
        }

        return view();
    }


    // 添加、保存数据
    public function lastcreate(Request $request)
    {

        if ($request->isPost()) {
            $post = trimAll($request->post());
            $post['alias'] = getRandStr(8);
            if (session('admin')->id == 1) {

            } else {
                $post['admin'] = session('admin')->id;
            }


            unset($post['file']);

            //写入数据库
            if (Last::create($post)) {
                createLog('添加 返回页 成功：' . $post['title']);
                success('操作成功');
            } else {
                createLog('添加 返回页 失败：' . $post['title']);
                error('操作失败');
            }

        }

        return view();
    }


    // 编辑、保存数据
    public function lastedit(Request $request, $id)
    {

        if ($request->isPost()) {
            $post = trimAll($request->post());
            if (session('admin')->id == 1) {

            } else {
                $post['admin'] = session('admin')->id;
            }

            unset($post['file']);

            //写入数据库
            if (Last::where('id', $id)->update($post)) {
                createLog('编辑 返回页 成功：' . $post['title']);
                success('操作成功');
            } else {
                createLog('编辑 返回页 失败：' . $post['title']);
                error('操作失败');
            }

        }

        //加载数据
        $data = Last::get($id);

        $this->assign('data', $data);
        return view();
    }


    public function plindex(Request $request)
    {
        if ($post = $request->isAjax()) {

            $page = input('param.page/d', 1);
            $limit = input('param.limit/d', 20);
            if (session('admin')->id == 1) {
                $arrs = Pinglun::order(['id' => 'desc'])->page($page)->limit($limit)->select();
            } else {
                $arrs = Pinglun::where(['admin' => session('admin')->id])->order(['id' => 'desc'])->page($page)->limit($limit)->select();
            }


            if (count($arrs) > 0) {
                foreach ($arrs as $k => $v) {
                    $v['domain'] = Domains::getOneData(2, true, $v['admin']);
                    $v['adminname'] = db('users')->where(['id' => $v['admin']])->value('username');
                }
            }

            $data = array(
                'data' => $arrs,
                'count' => Pinglun::count('id'),
                'code' => 0,
                'msg' => '',
            );
            return json($data);
        }

        return view();
    }


    // 添加、保存数据
    public function plcreate(Request $request)
    {

        if ($request->isPost()) {
            $post = trimAll($request->post());
            $post['alias'] = getRandStr(8);
            if (session('admin')->id == 1) {

            } else {
                $post['admin'] = session('admin')->id;
            }


            unset($post['file']);

            //写入数据库
            if (Pinglun::create($post)) {
                createLog('添加 评论 成功：' . $post['title']);
                success('操作成功');
            } else {
                createLog('添加 评论 失败：' . $post['title']);
                error('操作失败');
            }

        }

        return view();
    }


    // 编辑、保存数据
    public function pledit(Request $request, $id)
    {

        if ($request->isPost()) {
            $post = trimAll($request->post());
            if (session('admin')->id == 1) {

            } else {
                $post['admin'] = session('admin')->id;
            }

            unset($post['file']);

            //写入数据库
            if (Pinglun::where('id', $id)->update($post)) {
                createLog('编辑 评论 成功：' . $post['title']);
                success('操作成功');
            } else {
                createLog('编辑 评论 失败：' . $post['title']);
                error('操作失败');
            }

        }

        //加载数据
        $data = Pinglun::get($id);

        $this->assign('data', $data);
        return view();
    }

    //视频要同步的用户列表
    public function user(Request $request)
    {
        if ($request->isAjax()) {
            $videoId = input('video_id', 0);
            $page = input('param.page/d', 1);
            $limit = input('param.limit/d', 20);
            $username = input('username', '');
            $where = [];
            if ($username != "") {
                $where = [
                    ["username", "like", "%$username%"]
                ];
            }
            $data = Users::field('password', true)
                ->where(['status' => 1])->where($where)
                ->order(['id' => 'desc'])->page($page)
                ->limit($limit)->select();
            $dataCount = Users::where(['status' => 1])
                ->where($where)
                ->count('id');

            $data = array(
                'data' => $data,
                'count' => $dataCount,
                'code' => 0,
                'msg' => '',
                'video_id' => $videoId
            );
            return json($data);
        }
        return view('user');
    }

    //同步视频
    public function sync()
    {
        $videoIds = input('video_ids', 0);
        $ids = input('param.ids', 1);
        if (!$videoIds || !$ids) {
            error('参数错误');
        }
        $videoIdsArr = explode(',', $videoIds);
        $ids = explode(',', $ids);
        foreach ($videoIdsArr as $videoId) {
            foreach ($ids as $adminId) {
                $where1 = [
                    ['admin', '=', $adminId],
                    ['sync_video_id', '=', $videoId],
                ];
                $where2 = [
                    ['admin', '=', $adminId],
                    ['id', '=', $videoId],
                ];
                $videoCount = Videos::whereOr([$where1, $where2])->count('*');
                $videoInfo = Videos::where(['id' => $videoId])->find();
                if ($videoInfo) {
                    if ($videoCount == 0) {
                        Videos::create([
                            'alias' => $videoInfo['alias'],
                            'title' => $videoInfo['title'],
                            'gs' => $videoInfo['gs'],
                            'gsurl' => $videoInfo['gsurl'],
                            'ggwlj' => $videoInfo['ggwlj'],
                            'ggwtp' => $videoInfo['ggwtp'],
                            'share_title' => $videoInfo['share_title'],
                            'share_desc' => $videoInfo['share_desc'],
                            'share_img' => $videoInfo['share_img'],
                            'content' => $videoInfo['content'],
                            'img' => $videoInfo['img'],
                            'url' => $videoInfo['url'],
                            'miao' => $videoInfo['miao'],
                            'share_end_url' => $videoInfo['share_end_url'],
                            'new_shre_url' => $videoInfo['new_shre_url'],
                            'back_jump_url' => $videoInfo['back_jump_url'],
                            'wenzhang' => $videoInfo['wenzhang'],
                            'imgs' => $videoInfo['imgs'],
                            'pinglun' => $videoInfo['pinglun'],
                            'admin' => $adminId,
                            'height' => $videoInfo['height'],
                            'wzqz' => $videoInfo['wzqz'],
                            'tourl' => $videoInfo['tourl'],
                            'is_jx' => $videoInfo['is_jx'],
                            'expiretime' => $videoInfo['expiretime'],
                            'bggwlj' => $videoInfo['bggwlj'],
                            'bggwtp' => $videoInfo['bggwtp'],
                            'audio'=>$videoInfo['audio'],
                            'sync_video_id' => $videoId,
                        ]);

                    } else {
                        Videos::where(['admin' => $adminId, 'sync_video_id' => $videoId])->update([
                            'alias' => $videoInfo['alias'],
                            'title' => $videoInfo['title'],
                            'gs' => $videoInfo['gs'],
                            'gsurl' => $videoInfo['gsurl'],
                            'ggwlj' => $videoInfo['ggwlj'],
                            'ggwtp' => $videoInfo['ggwtp'],
                            'share_title' => $videoInfo['share_title'],
                            'share_desc' => $videoInfo['share_desc'],
                            'share_img' => $videoInfo['share_img'],
                            'content' => $videoInfo['content'],
                            'img' => $videoInfo['img'],
                            'url' => $videoInfo['url'],
                            'miao' => $videoInfo['miao'],
                            'share_end_url' => $videoInfo['share_end_url'],
                            'new_shre_url' => $videoInfo['new_shre_url'],
                            'back_jump_url' => $videoInfo['back_jump_url'],
                            'wenzhang' => $videoInfo['wenzhang'],
                            'imgs' => $videoInfo['imgs'],
                            'pinglun' => $videoInfo['pinglun'],
                            'height' => $videoInfo['height'],
                            'wzqz' => $videoInfo['wzqz'],
                            'tourl' => $videoInfo['tourl'],
                            'is_jx' => $videoInfo['is_jx'],
                            'expiretime' => $videoInfo['expiretime'],
                            'bggwlj' => $videoInfo['bggwlj'],
                            'bggwtp' => $videoInfo['bggwtp'],
                            'audio'=>$videoInfo['audio'],
                        ]);
                    }
                }
            }
        }
        return json(['code' => 0, 'msg' => '同步成功', 'data' => ['video_ids' => $videoIds, 'ids' => $ids]]);
    }
}
